package com.jquery.jqgrid.model;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.we823.utils.web.RequestUtil;

public class Filter {
	private String groupOp;
	private List<Rule> rules;

	public Filter() {
	}

	public Filter(HttpServletRequest request) {
		parseRequest(request);
	}

	private void parseRequest(HttpServletRequest request) {

		String filters = RequestUtil.getValueByParam(request, "filters", "");
		if (StringUtils.isNotEmpty(filters)) {
			
			JSONObject jsonObject = JSON.parseObject(filters);
			try {
				this.groupOp = jsonObject.getString("groupOp");
				JSONArray jsonArray = jsonObject.getJSONArray("rules");
				if (jsonArray != null) {
					rules = new ArrayList<>();
					int arraySize = jsonArray.size();
					for (int index = 0; index < arraySize; index++) {
						JSONObject object = jsonArray.getJSONObject(index);
						Rule rule = new Rule();
						rule.setField(object.getString("field"));
						rule.setOp(object.getString("op"));
						rule.setData(object.getString("data"));

						rules.add(rule);
					}
				} else {
					rules = null;
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

	}

	public String getGroupOp() {
		return groupOp;
	}

	public void setGroupOp(String groupOp) {
		this.groupOp = groupOp;
	}

	public List<Rule> getRules() {
		return rules;
	}

	public void setRules(List<Rule> rules) {
		this.rules = rules;
	}

}
